// packageJ/chain-store/mycomponent/manySpecs/manySpecs.js
const app = getApp();
const cartPost = require('../cart');
const skinBehavior = require('../../../../utils/themeSkin/skinBehavior');
// var optionsId = ""; //选择后的 规格ID
var specsManage = [];
var optionsMaxCount = 1;
Component({
  behaviors: [cartPost, skinBehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    goodsInfo: {
      type: null,
      value: []
    },
    store_id: {
      type: null
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    show2: false,
    optionsId:""
  },
  observers: {
    'goodsInfo': function (info) {
      console.log(info, 'manyspecs')
      if (info.length != 0) {
        this.setData({
          show2: true
        })
        this.getCart();
        this.initPopView1()
      }

    }
  },
  lifetimes: {
    attached() {
      let language = wx.getStorageSync("langIndex");
      this.setData({ language: language.en });
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    close(){
      this.setData({
        show2:false
      })
      this.triggerEvent('close')
    },
    updateCart(){
      this.getCart();
    },
    submitAction() {
      console.log(this.data.goodsInfo, this.data.store_id, this.data.optionsId,true)
      this.addCart(this.data.goodsInfo.id,this.data.store_id,this.data.optionsId,true)
    },
    initPopView1() {
      specsManage = [];
      this.setData({
        specid: "",
        popNum: 0,
        optionsId:''
      });
      if (this.data.goodsInfo.has_option === 1) {
        // this.isShowMultiSpecsMemPrice(); //是否需要显示多规格会员价
        //是否有规格
        this.setData({
          popTitle: this.data.goodsInfo.title,
          popThumb: this.data.goodsInfo.thumb,
          popStock: this.data.goodsInfo.stock,
          popCard: {},
        });
        if (!this.data.specid.length) {
          this.setData({
            popPrice: this.data.goodsInfo.min_price + "-" + this.data.goodsInfo.max_price,
          });
        }
        this.setData({
          goodsDescription: "请选择",
        });
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          this.setData({
            goodsDescription: this.data.goodsDescription + " " + this.data.goodsInfo.has_many_specs[i].title,
          });
        }

        if (!this.data.optionsId) {
          // 默认选择第一个
          for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
            this.selectSpecs(this.data.goodsInfo.has_many_specs[i].specitem[0], "first", i);
          }
        }
      } else {
        this.setData({
          goodsDescription: "",
        });
        optionsMaxCount = this.data.goodsInfo.stock; //设置最大购买量
      }
    },
    //界面选择规格触发事件
    selectSpecs(e, str, i) {
      let id = 0;
      let index = 0;
      let indexl = 0;
      // let data = {};
      if (str == "first") {
        id = e.id;
        index = 0;
        indexl = i;
        // data = e;
      } else {
        id = e.currentTarget.dataset.itemid;
        index = e.currentTarget.dataset.index;
        indexl = e.currentTarget.dataset.indexl;
        // data = e.currentTarget.dataset.item;
      }
      

      //处理选择池
      this.manageSpecs(indexl, index);
      //处理规格组合选择状态
      this.setGoodsSpecs(indexl, index);
      //设置选择规格后的 价格、照片、库存
      this.setGoodsSpecsChangeInfo(id);
      //判断当前购买总量与库存的关系
      this.getMaxCount();
      console.log(this.data.optionsId)
    },
    //判断当前购买总量与库存的关系
    getMaxCount() {
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        if (optionsMaxCount == 0) {
          //库存不足
          this.setData({
            popNum: 0,
          });
        }
        if (this.data.popNum > optionsMaxCount) {
          this.setData({
            popNum: optionsMaxCount,
          });
        }
      }
    },
    //设置选择规格后的 价格、照片、库存
    setGoodsSpecsChangeInfo(id) {
      //根据ID 排序 specsManage.sort();
      specsManage.sort(function (a, b) {
        return a.id - b.id;
      });
      if (specsManage.length === this.data.goodsInfo.has_many_specs.length) {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"
        this.setData({
          specid: goodsSpecs,
        });
        for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
          if (goodsSpecs === this.setGoodsSpecsBySort(this.data.goodsInfo.has_many_options[i].specs)) {
            this.setData({
              popmPrice: this.data.goodsInfo.has_many_options[i].market_price, //设置价格
              popPrice: this.data.goodsInfo.has_many_options[i].product_price, //设置价格
              popThumb: app._isTextEmpty(this.data.goodsInfo.has_many_options[i].thumb) ? this.data.goodsInfo.thumb : this.data.goodsInfo.has_many_options[i].thumb, //设置图片
              popStock: this.data.goodsInfo.has_many_options[i].stock,
              optionsId:this.data.goodsInfo.has_many_options[i].id
            });
            optionsMaxCount = this.data.goodsInfo.has_many_options[i].stock; //库存最大数 用于切换更改买家购买数量
            if (optionsMaxCount > 0) {
              this.setData({
                popNum: 0,
              });
            }
            if (this.data.isMultiSpecs) this.getMemberPrice(this.data.optionsId);
            break;
          }
        }
        for (let i = 0; i < this.data.carts.length; i++) {
          if (this.data.carts[i].goods_id === this.data.goodsInfo.id && this.data.carts[i].option_id === this.data.optionsId) {
            this.setData({
              popNum: this.data.carts[i].total,
              popCard: this.data.carts[i],
            });
            break;
          }
          this.setData({
            popNum: 0,
            popCard: {},
          });
        }
      } else {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        this.setData({
          specid: goodsSpecs,
        });
      }
    },
    getMemberPrice(_optionsId) {
      if (!_optionsId) return;
      let specsVIPPrc = 0;
      this.setData({ specsVIPPrc });
      let urlStr = app.getNetAddresss("goods.other-info.option-vpi-price");
      urlStr += "&option_id=" + _optionsId;
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            specsVIPPrc = res.data.vip_price || null;
          } else {
            specsVIPPrc = null;
          }
          this.setData({ specsVIPPrc });
        },
        fail: function (res) {
          specsVIPPrc = null;
          this.setData({ specsVIPPrc });
        },
      });

    },
    //处理商品goodsSpecs 并排序 新方法
    setGoodsSpecsBySort(specs) {
      let _specs = specs.split("_"); //先变成数组
      //_specs.sort();//排序
      _specs.sort(function (a, b) {
        return a - b;
      });
      // 在组装回去
      let goodsSpecs = "";
      for (let j = 0; j < _specs.length; j++) {
        goodsSpecs += _specs[j] + "_";
      }
      goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"

      return goodsSpecs;
    },
    //处理规格组合选择状态 过滤数据
    setGoodsSpecs(indexl, index) {
      let specs = this.data.goodsInfo.has_many_specs[indexl].specitem[index];
      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        if (specs.specid != this.data.goodsInfo.has_many_specs[i].id) {
          this.setGoodsSpecsStatus(i, specs.id);
        }
      }
    },
    //处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
    setGoodsSpecsStatus(index, id) {
      let specitem = this.data.goodsInfo.has_many_specs[index].specitem;
      let options = []; //数据池
      for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
        let _specs = this.data.goodsInfo.has_many_options[i].specs.split("_");
        for (let j = 0; j < _specs.length; j++) {
          if (_specs[j] == id) {
            options.push(this.data.goodsInfo.has_many_options[i]);
            return;
          }
        }
      }
      for (let m = 0; m < options.length; m++) {
        let _specs = options[m].specs.split("_");
        for (let y = 0; y < _specs.length; y++) {
          if (_specs[y] != id && options[m].stock == 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                this.setData({
                  ["data.goodsInfo.has_many_specs[" + index + "].specitem[" + n + "].c"]: true,
                });
                return;
              }
            }
          } else if (_specs[y] != id && options[m].stock > 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                this.setData({
                  ["data.goodsInfo.has_many_specs[" + index + "].specitem[" + n + "].c"]: false,
                });
                return;
              }
            }
          }
        }
      }
    },
    //处理选择池
    manageSpecs(indexl, index) {
      console.log(this.data.goodsInfo.has_many_specs,indexl)
      let data = this.data.goodsInfo.has_many_specs[indexl].specitem[index];
      var specsObject = new Object();
      specsObject.id = data.id;
      specsObject.specid = data.specid;
      specsObject.title = data.title;

      if (specsManage.length > 0) {
        for (let i = 0; i < specsManage.length; i++) {
          if (specsManage[i].specid == specsObject.specid) {
            specsManage.splice(i, 1);
          }
        }
        specsManage.push(specsObject);
      } else {
        specsManage.push(specsObject);
      }

      //排序
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        var newSpecsManage = [];
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.data.goodsInfo.has_many_specs[i].id == specsManage[j].specid) {
              newSpecsManage.push(specsManage[j]);
              break;
            }
          }
        }
        specsManage = newSpecsManage;
      }
      this.setGoodsDescription();
    },
    //处理goodsDescription 数据
    setGoodsDescription() {
      var description = "";
      //相等代表全选了 体现语句
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        description = "已选择 ";
        for (let i = 0; i < specsManage.length; i++) {
          description += specsManage[i].title + " ";
        }
        this.setData({
          goodsDescription: description,
        });
      } else {
        description = "请选择 ";

        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.data.goodsInfo.has_many_specs[i].id != specsManage[j].specid) {
              description += this.data.goodsInfo.has_many_specs[i].title + " ";
              break;
            }
          }
        }
        this.setData({
          goodsDescription: description,
        });
      }
    },
  }
})
